<template>
	<view class="message-list">
		<view class="message-box" v-for="(item,index) in messageList" :key="index">
			<view class="my-box message-row">
				<view class="avatar">MY</view>
				<view class="message-content">{{item.my}}</view>
			</view>
			<view class="ai-box message-row">
				<view class="avatar">AI</view>
				<view class="message-content" v-if="loading"><u-loading></u-loading></view>
				<view class="message-content" v-else>{{item.ai}}</view>
			</view>
		</view>
		<view class="input-box">
			<u-input class="gpt-input" v-model="message"></u-input>
			<u-button class="custom-btn" @click="submitMessage()">发送</u-button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				messageList: [
				],
				message: '',
				loading: false
			};
		},
		methods: {
			submitMessage() {
				if(this.loading) return
				this.messageList.push({
					my: this.message,
					ai: ''
				})
				this.loading = true
				this.$u.get(`chat/chat?content=${this.message}`).then(res => {
					console.log(res)
					this.messageList[this.messageList.length - 1].ai = res.message.content
				}).catch(() => {
					uni.showToast({
						icon:'error',
						title: '发送失败'
					})
					this.messageList.length = this.messageList.length - 1
				}).finally(() => {
					this.loading = false
					this.message = ''
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
.message-list{
	display: flex;
	flex-direction: column;
	padding-bottom: 120rpx;

	.message-box{
		display: flex;
		flex-direction: column;
		padding: 0 10rpx;
		.message-row{
			display: flex;
			gap: 20rpx;
			.avatar{
				width: 80rpx;
				height: 80rpx;
				border-radius: 50%;
				background: #C4C1D4;
				text-align: center;
				line-height: 80rpx;
			}
			.message-content{
				max-width: 50%;
				background: #E4E5E2;
				padding: 20rpx;
				border-radius: 10rpx;
				  word-wrap: break-word; /* 允许在长单词内部换行 */
				  word-break: break-all; /* 允许在任意位置换行 */
			}
		}
		.my-box{
			flex-flow: row-reverse;
			.message-content{
				background: #A5EE6F;
			}
		}
	}
	.input-box{
		height: 100rpx;
		display: flex;
		gap: 30rpx;
		padding: 0 30rpx;
		align-items: center;
		position: fixed;
		bottom: 50px;
		width: 100%;
		background: white;
		box-shadow: 0 0 10px 1px #ccc;
		.gpt-input{
			border: #C4C1D4 1px solid;
			border-radius: 20rpx;
			padding: 0 20rpx !important;
		}
		.custom-btn{
			width: 120rpx;
			color: white;
		}
	}
}
</style>
